<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="username" label="教师姓名" required>
        <uni-easyinput placeholder="教师姓名" v-model="formData.username" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="subject_id" label="学科" required>
		<uni-data-checkbox multiple v-model="formData.subject_id" collection="uni-cms-categories" field="_id as value, name as text"></uni-data-checkbox>
	 </uni-forms-item>
      <uni-forms-item name="gender" label="性别">
        <uni-data-checkbox v-model="formData.gender" :localdata="formOptions.gender_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="mobile" label="电话" required>
        <uni-easyinput placeholder="电话" v-model="formData.mobile" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="email" label="邮箱">
        <uni-easyinput placeholder="邮箱地址" v-model="formData.email" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="avatar" label="头像">
        <uni-file-picker 
			ref="avatarfile"
        	v-model="formData.avatar"  
			file-mediatype="image"
			file-extname="png,jpg,jpeg"
			mode="grid"
			:limit="1"
        ></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="comment" label="备注">
        <textarea placeholder="备注" @input="binddata('comment', $event.detail.value)" class="uni-textarea-border" v-model="formData.comment" trim="both"></textarea>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator url="/pages/teacher/list" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/teacher.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'teacher';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  // 将cloud地址转换为可访问的https地址
  	function cloudToHttps(str) {
  		let newStr = str.replace("cloud://", "https://");
  		let [,,env] = str.split('/');
  		return newStr.replace(env, env+".normal.cloudstatic.cn");
  	}

  export default {
    data() {
      let formData = {
        "username": "",
        "gender": 0,
        "mobile": "",
        "email": "",
        "comment": "",
        "avatar": [],
        "subject_id": []
      }
      return {
        formData,
        formOptions: {
          "gender_localdata": [
          
            {
              "text": "男",
              "value": 0
            },
            {
              "text": "女",
              "value": 1
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      upload() {
		  console.log('upload');
		  this.$refs.avatarfile.upload()
	  },
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
		
        this.$refs.form.validate().then((res) => {
			
			let newRes = {
				...res,
				avatar: res.avatar && res.avatar.length ? res.avatar.map(item => ({...item, url: cloudToHttps(item.fileID)})) : []
			}
			console.log('submit',newRes);
          return this.submitForm(newRes)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).field("username,gender,mobile,email,comment,avatar,subject_id").get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
